# -*- coding: utf-8 -*-

import time
import hashlib
import requests
import urllib
import copy
import operator
import json

#每2秒6个请求


class wbf():
    
    _headers = {
    'Content-Type': 'application/json; charset=utf-8',
	'Accept': 'application/json',
    "User-Agent":"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/73.0.3683.103 Safari/537.36"
    }

    def __init__(self, api_Key, secret_key):
        self.url = 'https://openapi.wbf.info'
        # self.url = 'wss://ws.wbf.info'
        self.api_Key = api_Key
        self.secret_key = secret_key
        
    def get_all_ticker(self):
        params={}
        url = self.url + '/open/api/get_allticker'
        return self.get(url,params)
    def get_records(self,symbol,period):
        params={}
        params['symbol']=symbol
        params['period']=period
        url =self.url + '/open/api/get_records'
        return self.get(url,params)
    def get_ticker(self,symbol):
        params={}
        params['symbol']=symbol
        url =self.url + '/open/api/get_ticker'
        return self.get(url,params)
    def get_market(self):
        params={}
        url =self.url + '/open/api/market'
        return self.get_sign(url,params)
        
    def get_balance(self):
        params={}
        url = self.url + '/open/api/user/account'
        return self.get_sign(url,params)

    
    def get_trades(self,symbol):
        params={'symbol':symbol}
        url = self.url +'/open/api/get_trades'
        return self.get(url,params)

    def get_allorder(self,symbol='',startDate='',endDate='',pageSize='',page=''):
        params={'symbol':symbol}
        if startDate:
            params['startDate'] = startDate
        if endDate:
            params['endDate'] = endDate
        if pageSize:
            params['pageSize'] =pageSize
        if page:
            params['page'] = page 
        url = self.url+ '/open/api/v2/all_order'
        return self.get_sign(url,params)
            
    def get_kline(self,symbol='',period=''):
        params={}
        params['symbol']=symbol
        params['period']=period
        url = self.url + '/open/api/get_records'
        return self.get(url,params)
    
    def get_commom(self):
        params={}
        url = self.url+'/open/api/common/symbols'
        return self.get(url,params)
    
    def cancel_order_all(self,symbol=''):
        params={'symbol':symbol}
#        url=self.url+'/open/api/cancel_order_all'+'?'+urllib.parse.urlencode(self.sign({}))
        url=self.url+'/open/api/cancel_order_all'
        return self.postt(url,params)
    
    def sign(self,params):  
        params = copy.copy(params)
        params['api_key']=self.api_Key
        params['time'] = str(int(time.time()))
        sort_params = sorted(params.items(), key=operator.itemgetter(0))
        params =dict(sort_params)
        params['secret_key']=self.secret_key
        string = urllib.parse.urlencode(params)
        s = string.replace('&','')
        s = s.replace('secret_key','')
        temp_sign =s.replace('=','')
        md_sign = hashlib.md5()
        md_sign.update(temp_sign.encode())
        sign = md_sign.hexdigest()
        params={}
        params['api_key'] = self.api_Key
        params['time'] =  str(int(time.time()))
        params['sign'] = sign
        return params

    def get(self,url,params):
        headers = dict(self._headers)
        postdata = urllib.parse.urlencode(params)
        try:
            response = requests.get(url, postdata, headers=headers, timeout=5)
            if response.status_code == 200:
                data = response.json()
                if data.get('code') !=  str(0) :
                    print(data.get('msg'),response.status_code)
                return data.get('data')
            else:
                print( {"status":"fail"},response.status_code)
        except Exception as e:
            print("httpGet failed, detail is:%s" %e)
            print( {"status":"fail","msg": "%s"%e})
    
    def get_sign(self,url,params):
        headers = dict(self._headers)
        a = self.sign(params)
#       将必传签名参数以及新的参数，两者合成新的字典---新的字典不用排序---只有签名时候，参数要排序；
        params = dict(params,**a)
        postdata = urllib.parse.urlencode(params)
        try:
            response = requests.get(url, postdata, headers=headers, timeout=5)
            if response.status_code == 200:
                data = response.json()
                if data.get('code') != str(0) :
                    print(data.get('msg'),response.status_code)
                return data.get('data')
            else:
                print( {"status":"fail"},response.status_code)
        except Exception as e:
            print("httpGet failed, detail is:%s" %e)
            print( {"status":"fail","msg": "%s"%e})
    
    def postt(self,url,params):
        headers = dict(self._headers)
        a = self.sign(params)
        params = dict(params,**a)
#        postdata = bytes(urllib.parse.urlencode(params),encoding = 'utf-8')
        postdata = json.dumps(params)
        try:
            response = requests.post(url,  params = postdata, headers=headers, timeout=5)
            if response.status_code == 200:
                data = response.json()
                if data.get('code') != str(0):
                    print(data.get('msg'),response.status_code)
                return data.get('data')
#                return data
            else:
                print( {"status":"fail"},response.status_code)
        except Exception as e:
            print("httpGet failed, detail is:%s" %e)
            print( {"status":"fail","msg": "%s"%e})
    
    

    
    
    
    
    
    
    
    